import dynamic from 'next/dynamic'
import styles from './index.module.scss'
import HFilmList from '@c/h-film-list'
import Responsive from '@c/responsive'
import Button from '@c/button'
import message from '@c/message'
import Image from '@c/image'
import cm from 'classnames'
import { useRouter } from 'next/router'
import { useEffect, useMemo, useState, useRef } from 'react'
import { isPureNumber, goBack, injectStructData, deleteScript, removeDuplicates, getSpaceAndPage } from '@/utils/utils'
import { useShowLogin, useVipDialog } from '@/utils/hooks'
import { FILM_URL } from '@/constant'
import { userInfo } from '@/store'
import { useRecoilValue } from 'recoil'
import omit from 'lodash-es/omit'
import Copy from 'clipboard'
import { vodDetailReport, scoreTaskFinishedReport } from '@/utils/report'
import {
  getRecommendInfo,
  getVodCollection,
  dianboGetSource,
  oldIdToNewId,
  getVodCollectionLines,
} from '@/api/vod'
import { getVodHistoryDuration,getVodCollected,vodCancelCollected,vodCollected } from '@/api/history-collect'
import DownloadBox from '@c/download/download-box'
import Link from 'next/link'
import { taskFinished } from '@/api/score'

const Footer = dynamic(() => import('@c/footer'))
const Select = dynamic(() => import('@c/select'))
const SvgSort = dynamic(() => import('@c/svg/sort'))
const DetailView = dynamic(() => import('@c/detail-view'))
const ArrowSvg = dynamic(() => import('@c/svg/arrow'))
const FetchLoading = dynamic(() => import('@c/request-loading'))

const formatStructData = (info, line) => {
  const data = {
    '@context': 'http://schema.org',
    name: info.name,
    actor:
      info.actor?.map(item => {
        return {
          '@type': 'Person',
          name: item.name
        }
      }) || {},
    director: info.director?.map(item => {
      return {
        '@type': 'Person',
        name: item.name
      }
    }),
    countryOfOrigin: {
      '@type': 'Country',
      name: info.country
    },
    genre: info.renderLabel,
    description: info.desc,
    image: info.posterUrl
  }
  if (info.isMovie) {
    try {
      const trailerUrl = line.videos
      if (trailerUrl) {
        data.trailer = {
          '@type': 'VideoObject',
          name: '预告片',
          embedUrl: `https://www.youtube.com/embed/${trailerUrl}`
        }
      }
    } catch (error) {}
    data.url = `https://www.histar.tv/vod/play-official/${info?.id}/1`
    data['@type'] = 'Movie'
    data.duration = info.countStr
  } else {
    data['@type'] = 'TVSeries'
    data.startDate = info.time
    data.inLanguage = info.language
    try {
      data.numberOfEpisodes = line.total
    } catch (error) {}
    if (line?.eporder?.length) {
      data.episode = line.eporder.map(item => {
        const params = {
          '@type': 'TVEpisode',
          episodeNumber: item.eporder,
          url: `https://www.histar.tv/vod/play-official/${info?.id}/${item.eporder}`
        }
        if (item.overView) {
          params.description = item.overView
        }
        return params
      })
    }
  }
  deleteScript('detail')
  injectStructData(data, 'detail')
}

const Index = props => {
  const { cid, recommend, collectionInfo, lines, selectionInfo } = props
  const user = useRecoilValue(userInfo)
  const setVipDialog = useVipDialog()
  const { chname, isMovie, imgUrl, posterUrl } = collectionInfo
  const [isCollected, setCollected] = useState(false) //点播是否收藏
  const router = useRouter()
  const setShowLogin = useShowLogin()
  const [playNum, setPlayNum] = useState(1)
  const ref = useRef(null)
  const [canExpend, setCanExpend] = useState(false)
  const [isAsk, setAsk] = useState(false)
  const [expend, setExpend] = useState(true)
  const heightRef = useRef(null)
  const [detailHeight, updateHeight] = useState('44.7916vw')
  const [currLines, updateCurrLines] = useState(lines)
  const [currEporderInfo, setEporderInfo] = useState(null)
  const [playHistoryIndex, setPlayHistoryIndex] = useState(1)
  const [isLoading, setLoading] = useState(false)
  const [playParams, setPlayParams] = useState({
    page: 1,
    sort: 1
  })
  useEffect(() => {
    formatStructData(collectionInfo, lines)
    const token = localStorage.getItem('token')
    getVodCollected(cid, token).then(res => setCollected(res?.data?.isFavorite))
  }, [router.asPath])

  const collected = async () => {
    const token = localStorage.getItem('token')
    if (!token) {
      setShowLogin(true)
      return
    }
    let res = null
    if (isCollected) {
      res = await vodCancelCollected(+cid, token)
    } else {
      res = await vodCollected(+cid, token)
    }
    if (!res.code) {
      message({ content: isCollected ? '取消收藏成功' : '收藏成功！' })
      setCollected(!isCollected)
    } else {
      message({ content: res.msg })
    }
  }

  const openDetail = (e, item) => {
    e.stopPropagation()
    setEporderInfo(item)
  }

  //分享上报
  const share = () => {
    const token = localStorage.getItem('token')
    if (token) {
      taskFinished({
        completionStatus: 2,
        ydtoken: ''
      })
    }
    scoreTaskFinishedReport({
      points_name: '点播分享'
    })
    vodDetailReport({
      share_status: '链接'
    })
  }

  useEffect(() => {
    const copyUrl = new Copy('.share-btn')
    copyUrl.on('success', () => {
      message({ content: '链接复制成功，分享给好友可领积分兑免费会员~' })
      share()
    })
    return () => {
      deleteScript('detail')
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  // 求片
  const getUrl = async () => {
    if (!localStorage.getItem('token')) {
      setShowLogin()
      return
    }
    if (isAsk) {
      return
    }
    const res = await dianboGetSource({
      cid: parseInt(cid)
    })
    if (res.code === 0) {
      message({ content: '求片提交成功，我们会尽快补充资源！' })
      setAsk(true)
    }
  }

  // 手机用
  useEffect(() => {
    if (!ref.current) {
      return
    }
    const height = ref.current.clientHeight
    setCanExpend(height >= 75)
  }, [router.asPath, ref])

  //开通vip引导
  const guideNode = useMemo(() => {
    if (!user.hasOwnProperty('token')) {
      return null
    }
    if (user.token) {
      if (!user.isVip) {
        return (
          <div className={cm(styles.guide, styles.guideOpen)} onClick={() => setVipDialog(1)}>
            <img src="/images/vip-juji.png" alt="vip" className={styles.vip} />
            <span className={styles.span}>开通会员</span>畅享最佳播放体验
          </div>
        )
      }
      if (user.vipDay <= 3) {
        return (
          <div className={cm(styles.guide, styles.guideOpen)} onClick={() => setVipDialog(1)}>
            <img src="/images/vip-juji.png" alt="vip" className={styles.vip} />
            <span className={styles.span}>续费会员</span>畅享最佳播放体验
          </div>
        )
      }
      return null
    }
    return (
      <div className={styles.guide} onClick={setShowLogin}>
        <img src="/images/vip-juji.png" alt="vip" className={styles.vip} />
        注册<span className={styles.span}>免费领会员</span>畅享最佳播放体验
      </div>
    )
  }, [collectionInfo, user])

  const getPlayHistory = token => {
    getVodHistoryDuration({ cid }, token).then(res => {
      try {
        if (res.data) {
          const index = Math.ceil(res.data.num / selectionInfo.pageSize)
          setPlayHistoryIndex(index)
          setPlayNum(res.data.num)
          if (index > 1) {
            updateLines(index)
          }
        }
      } catch (error) {}
    })
  }

  useEffect(() => {
    const token = localStorage.getItem('token')
    getPlayHistory(token)
    updateHeight(heightRef.current.offsetHeight)
    const updateH = () => {
      updateHeight(heightRef.current.offsetHeight)
    }
    window.addEventListener('resize', updateH)
    return () => {
      window.removeEventListener('resize', updateH)
    }
  }, [])

  const updateLines = page => {
    setPlayParams({
      ...playParams,
      page
    })
    setLoading(true)
    getVodCollectionLines({ cid, page, pageSize: selectionInfo.pageSize, sort: playParams.sort }).then(res => {
      updateCurrLines(res.data)
      setLoading(false)
    })
  }

  const updateSort = () => {
    setPlayParams({
      ...playParams,
      sort: playParams.sort === 1 ? 2 : 1
    })
    const newData = {
      ...currLines
    }
    newData.eporder = [...newData.eporder].reverse()
    updateCurrLines(newData)
  }

  return (
    <>
      <section className={cm(styles.detail, 'hideWhenPhone')} style={{ height: detailHeight }}>
        {/* 蒙层样式 */}
        <img
          loading="lazy"
          src={posterUrl}
          style={{ height: detailHeight }}
          className={styles.maskBg}
          alt={collectionInfo.name + '海报'}
        />
        <div className={styles.maskLinear}></div>
        {/* 主体内容 */}
        <div className={styles.content} ref={heightRef}>
          <div className={cm(styles.back, styles.backPhone)} onClick={() => goBack()}>
            <img loading="lazy" alt="返回" src="/images/back.png" />
            <span>返回</span>
          </div>
          <div className={styles.main}>
            <figure className={styles.poster}>
              <img loading="lazy" src={imgUrl} alt={collectionInfo.name} />
            </figure>
            <div className={styles.mainRight}>
              <h1 className={cm(styles.title, 'textEllipsis')}>{collectionInfo.name}</h1>
              <div className={styles.scoreBox}>
                {collectionInfo.tmdbScore ? (
                  <div className={styles.mark}>
                    <img loading="lazy" src="/images/tmdb.png" alt="tmdb" className={styles.tmdb} />
                    <span className={styles.tmdbText}>{('' + collectionInfo.tmdbScore).toFix(1)}</span>
                  </div>
                ) : null}
                {collectionInfo.doubanScore ? (
                  <div className={styles.mark}>
                    <img loading="lazy" src="/images/douban.png" alt="douban" className={styles.douban} />
                    <span className={styles.doubanText}>{('' + collectionInfo.doubanScore).toFix(1)}</span>
                  </div>
                ) : null}
              </div>
              <div className={styles.infos}>
                <div className={styles.tag}>
                  {collectionInfo.renderLabel.length
                    ? collectionInfo?.renderLabel?.map((item, index) => {
                        return (
                          <div key={index} className={styles.item}>
                            {item}
                          </div>
                        )
                      })
                    : '暂无分类信息'}
                </div>
                <span>{collectionInfo.language}&nbsp;</span>
                <span>{collectionInfo.time || '暂无上映日期信息'}&nbsp;</span>
                <span>
                  {collectionInfo?.countStr?.split('/')[0] || (isMovie ? '暂无时长信息' : '暂无剧集更新信息')}
                </span>
              </div>
              {guideNode}
              <div className={styles.detailMenuGroup}>
                {false ? (
                  <Button hover="opacity" className={cm(styles.btn)} onClick={getUrl}>
                    {isAsk ? '已求片' : '求片'}
                  </Button>
                ) : (
                  <Button link href={`/vod/play-official/${cid}/${playNum}`} className={cm(styles.btn, styles.mbtn)}>
                    <img loading="lazy" src="/images/h-play.png" alt="" />
                    <span>播放</span>
                  </Button>
                )}
                <Button hover="opacity" className={cm(styles.btn)} onClick={collected}>
                  <img loading="lazy" src={'/images/collect_page' + (isCollected ? '_on' : '') + '.png'} alt="收藏" />
                  <span className={isCollected ? 'text-theme' : ''}>{isCollected ? '已' : ''}收藏</span>
                </Button>
                <Button
                  hover="opacity"
                  className={cm(styles.btn, styles.share, 'share-btn')}
                  data-clipboard-text={`《${collectionInfo.name}》剧情太精彩了，快来星视界一起看！免费高清观看地址：https://www.histar.tv/vod/detail/${cid}`}
                >
                  <img loading="lazy" src="/images/share.png" alt="" />
                  <span>分享</span>
                  <img loading="lazy" src="/images/corn.webp" alt="corn" className={styles.corn} />
                </Button>
                <Button onClick={() => router.push('/download')} className={cm(styles.btn, styles.download)}>
                  <img loading="lazy" src="/images/download.png" alt="下载" />
                  <span>APP</span>
                  <DownloadBox className={styles.floatBox} />
                </Button>
              </div>
              <p className={styles.mdesc}>剧情简介</p>
              <p className={styles.mdescInfo} title={collectionInfo.desc}>
                {collectionInfo.desc || '暂无剧情简介信息'}
              </p>
              <div className={styles.actors}>
                <div className={styles.actorItem}>
                  <div className={cm(styles.items, 'textEllipsis')}>
                    {Array.isArray(collectionInfo?.director)
                      ? collectionInfo?.director?.map((item, index) => {
                          return (
                            <div className="flex shrink-0" key={item.id}>
                              {index ? <span>/</span> : null}
                              <Link href={`/person/${item.id}`} className={styles.personLink}>
                                {item.name}
                              </Link>
                            </div>
                          )
                        })
                      : '暂无导演信息'}
                  </div>
                  <span>导演</span>
                </div>
                <div className={styles.actorItem}>
                  <div className={styles.items}>
                    {Array.isArray(collectionInfo?.actor)
                      ? collectionInfo?.actor?.map((item, index) => {
                          return (
                            <div className="flex shrink-0 " key={item.id}>
                              {index ? <span>/</span> : null}
                              <Link href={`/person/${item.id}`} className={styles.personLink}>
                                {item.name}
                              </Link>
                            </div>
                          )
                        })
                      : '暂无演员信息'}
                  </div>
                  <span>演员</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
      {/* h5代码 */}
      <section className={cm(styles.detailPhone, 'hideWhenPc')}>
        <div className={styles.posterBox}>
          <img src={posterUrl.replace('w1920_and_h800','w500_and_h282')} alt="剧照" />
        </div>
        <h1 className={cm(styles.title, 'textEllipsis')}>{collectionInfo.name}</h1>
        <div className={styles.scoreBox}>
          {collectionInfo.tmdbScore ? (
            <div className={styles.mark}>
              <img loading="lazy" src="/images/tmdb.png" alt="tmdb" className={styles.tmdb} />
              <span className={styles.tmdbText}>{('' + collectionInfo.tmdbScore).toFix(1)}</span>
            </div>
          ) : null}
          {collectionInfo.doubanScore ? (
            <div className={styles.mark}>
              <img loading="lazy" src="/images/douban.png" alt="douban" className={styles.douban} />
              <span className={styles.doubanText}>{('' + collectionInfo.doubanScore).toFix(1)}</span>
            </div>
          ) : null}
          <span className="ml-1">{collectionInfo.language}</span>
          {collectionInfo.time && <span className="ml-1">{collectionInfo.time}</span>}
          {collectionInfo.countStr && <span>&nbsp;|&nbsp;{collectionInfo?.countStr?.split('/')[0]}</span>}
        </div>
        <div className={cm(styles.tag, 'scrollBeautify')}>
          {collectionInfo.renderLabel.length
            ? collectionInfo?.renderLabel?.map((item, index) => {
                return (
                  <div key={index} className={styles.item}>
                    {item}
                  </div>
                )
              })
            : '暂无分类信息'}
        </div>
        <div className={styles.detailMenuGroup}>
          {false ? (
            <Button className={cm(styles.btn, styles.mbtn)} onClick={getUrl}>
              {isAsk ? '已求片' : '求片'}
            </Button>
          ) : (
            <Button link href={`/vod/play-official/${cid}/${playNum}`} className={cm(styles.btn, styles.mbtn)}>
              <img loading="lazy" src="/images/h-play.png" alt="" />
              <span>播放</span>
            </Button>
          )}
          <Button className={cm(styles.btn)} onClick={collected}>
            <img loading="lazy" src={'/images/collect' + (isCollected ? '_active' : '_page') + '.png'} alt="收藏" />
          </Button>
          <Button
            className={cm(styles.btn, styles.share, 'share-btn')}
            data-clipboard-text={`点链接来星视界，和我一起免费看《${collectionInfo.name}》：https://www.histar.tv/vod/detail/${cid}`}
          >
            <img loading="lazy" src="/images/share.png" alt="分享" />
            <img loading="lazy" src="/images/corn.webp" alt="corn" className={styles.corn} />
          </Button>
          <Button onClick={() => router.push('/download')} className={cm(styles.btn, styles.download)}>
            <img loading="lazy" src="/images/download.png" alt="下载" />
          </Button>
        </div>
      </section>

      <Responsive>
        {!collectionInfo.isMovie && (
          <>
            {!selectionInfo.noSelections && (
              <div className={styles.chooseDrama}>
                <Select
                  width={310}
                  needPrefix
                  className={styles.selectPhone}
                  currentValue={playHistoryIndex}
                  list={selectionInfo.selectionGroup || []}
                  onChange={updateLines}
                />
                <SvgSort sort={playParams.sort} className={styles.sort} onClick={updateSort} />
              </div>
            )}
            {Array.isArray(currLines.eporder) &&
              (isLoading ? (
                <FetchLoading className="h-80" />
              ) : (
                <div className={cm(styles.dramaList, 'scrollBeautify')}>
                  {currLines.eporder?.map((item, index) => {
                    return (
                      <div
                        onClick={() => router.push(`/vod/play-official/${cid}/${item.eporder}`)}
                        key={index}
                        className={styles.listItem}
                        data-desc={item.overView}
                      >
                        <a
                          href={`/vod/play-official/${cid}/${item.eporder}`}
                          className="w-0 h-0 overflow-hidden"
                          style={{ fontSize: 0 }}
                        >
                          跳转
                        </a>
                        <div className={styles.poster}>
                          <Image src={item.postUrl || posterUrl} alt="剧照" />
                          <img
                            src="/images/h-curr-play.png"
                            alt="播放"
                            className={cm(styles.playPhone, 'hideWhenPc')}
                          />
                        </div>
                        <div className={styles.dramaInfo}>
                          <p className={cm(styles.dramaTitle, 'textEllipsis')}>
                            <span>{item.videoName ? item.eporder : `第${item.eporder}集`}</span>
                            <span>{item.videoName}</span>
                          </p>
                          <p className={styles.dramaDesc} title={item.overView}>
                            {item.overView || '暂无剧集描述信息'}
                          </p>
                        </div>
                        {item.overView && (
                          <div
                            title={item.overView}
                            className={cm(styles.seeOverView, 'hideWhenPc')}
                            onClick={e => openDetail(e, item)}
                          >
                            <span>查看</span>
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>
              ))}
          </>
        )}
        {/* h5代码 */}
        <div className={cm(styles.actorBoxPhone, 'hideWhenPc')}>
          <div className={styles.actorBox} style={{ marginTop: 20 }}>
            <span className={styles.infoLabel}>导演：</span>
            {Array.isArray(collectionInfo?.director)
              ? collectionInfo?.director?.map((item, index) => {
                  return (
                    <div className="inline-block" key={item.id}>
                      {index ? <span>,</span> : null}
                      <Link href={`/person/${item.id}`} className={styles.personLink}>
                        {item.name}
                      </Link>
                    </div>
                  )
                })
              : '暂无导演信息'}
          </div>
          <div className={cm(styles.actorBox)}>
            <span className={styles.infoLabel}>主演：</span>
            {Array.isArray(collectionInfo?.actor)
              ? collectionInfo?.actor?.map((item, index) => {
                  return (
                    <div className="inline-block shrink-0 " key={item.id}>
                      {index ? <span>,</span> : null}
                      <Link href={`/person/${item.id}`} className={styles.personLink}>
                        {item.name}
                      </Link>
                    </div>
                  )
                })
              : '暂无演员信息'}
          </div>
          <div className={cm(styles.mdesc, expend ? styles.mExpend : '')}>
            <div ref={ref}>
              <span className={styles.infoLabel}>描述：</span>
              {collectionInfo.desc || '暂无剧情简介信息'}
            </div>
            {canExpend ? (
              <div
                className={cm(styles.expendBtn, expend ? styles.expendBtnOpen : '')}
                onClick={() => setExpend(!expend)}
              >
                <span>{!expend ? '收起' : '展开'}</span>
                <ArrowSvg width={16} className={styles.img} fill="var(--theme-color)" />
              </div>
            ) : null}
          </div>
        </div>
        <HFilmList data={recommend} hideCollect refresh fontSize={24} isDetail source={FILM_URL[chname]} top={40} />
        <Footer />
        {currEporderInfo && <DetailView data={currEporderInfo} onClose={() => setEporderInfo(null)} />}
      </Responsive>
    </>
  )
}

export default Index

// 组装详情数据
const generateCollectionData = res => {
  const data = {
    ...omit(res, ['label']),
    videosGroup: res.videosGroup || [],
    isMovie: res.chname === '电影',
    imgUrl: res.picurl || '/images/default.png',
    posterUrl: res.posterUrl || res.picurl
  }
  // 处理标签
  try {
    data.renderLabel = [data.chname, ...res.label.split(' / ')].filter(item => item)
  } catch (error) {
    data.renderLabel = [data?.chname || '']
  }

  return data
}

export async function getServerSideProps({ params }) {
  const { id } = params
  if (!isPureNumber(id)) {
    return { notFound: true }
  }

  // 处理分页数据
  const pagesInfo = await getVodCollectionLines({ cid: id, page: 1, pageSize: 1, sort: 1 })
  const selectionInfo = getSpaceAndPage(1, pagesInfo.data?.total || 0)

  const resArr = await Promise.all([
    getVodCollection(id, {}),
    getRecommendInfo(id, {}),
    getVodCollectionLines({ cid: id, page: selectionInfo.pageNo, pageSize: selectionInfo.pageSize, sort: 1 })
  ])

  // 做重定向
  try {
    if (!resArr[0].data?.id) {
      const res = await oldIdToNewId(id)
      const newId = res?.data?.id
      if (newId) {
        return {
          redirect: {
            destination: `/vod/detail/${newId}`,
            permanent: true
          }
        }
      }
      return { notFound: true }
    }
  } catch (error) {
    return { notFound: true }
  }
  const collectionInfo = generateCollectionData(resArr[0]?.data || {})
  collectionInfo.actor = removeDuplicates(collectionInfo.actor || [], 'name')
  collectionInfo.director = removeDuplicates(collectionInfo.director || [], 'name')
  let layoutProps = {}
  try {
    layoutProps = {
      noSomeMetaInfo: false,
      title: `${collectionInfo.name}-${collectionInfo.chname}在线观看及剧情介绍 - 星视界`,
      desc: collectionInfo?.desc || '',
      url: FILM_URL[collectionInfo.chname] || ''
    }
  } catch (error) {}
  return {
    props: {
      selectionInfo,
      collectionInfo,
      cid: id,
      recommend: {
        name: '相关推荐',
        ban: true,
        cards: resArr[1]?.data?.cards || []
      },
      layoutProps,
      lines: resArr[2].data || {}
    }
  }
}
